import {defineStore} from 'pinia'
import {SysConfig} from "@/libs/config";

export const useTabStore = defineStore('tab', {
    state: () => ({
        cacheRoutes: [],
        allowMaxTab: 15,
    }),


    actions: {

        addIndex() {
            const index = this.cacheRoutes.findIndex(item => item.path === SysConfig.homeUrl)
            if (index < 0) {
                this.cacheRoutes.push({
                    "path": SysConfig.homeUrl,
                    "name": "portal-home", "meta": {"title": "主 页", "icon": "ri-home-line", "noClosable": true}
                })
            }
        },
        addVisitedRoute(route) {
            this.addIndex()
            if (route.path !== SysConfig.homeUrl) {
                const target = this.cacheRoutes.find(item => item.path === route.path)
                if (target && !route.meta.dynamicNewTab) Object.assign(target, route)
                else if (!target) this.cacheRoutes.push({...route})
                if (!this.cacheRoutes.find(route => route.meta.noClosable)) this.cacheRoutes[0].meta.noClosable = true
            }
        },
        delVisitedRoute(path: string) {
            this.cacheRoutes = this.cacheRoutes.filter(route => route.path !== path)
        },

        cleanLeft(path: string) {
            let found = false
            this.cacheRoutes = this.cacheRoutes.filter(route => {
                if (route.path === path) found = true
                return route.meta.noClosable || found
            })
        },
        cleanRight(path: string) {
            let found = false
            this.cacheRoutes = this.cacheRoutes.filter(route => {
                const close = found
                if (route.path === path) found = true
                return route.meta.noClosable || !close
            })
        },

        // 关闭其他
        cleanOther(path: string) {
            this.cacheRoutes = this.cacheRoutes.filter(route => route.meta.noClosable || route.path === path)
        },
        // 关闭所有
        removeAll() {
            this.cacheRoutes = this.cacheRoutes.filter(item => item.path === SysConfig.homeUrl)

        },
    },
})
